// pages/tuijian_reg/index.js
const app = getApp();
const util = require('../../utils/util.js');
let globalData = getApp().globalData;
var sendPost = app.globalData.sendPost;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pid:'',
    openid:'',
    index: 0,//默认显示位置
    share:false,//是否邀请进入
    name: '', //姓名
    tel: '',  //电话
    share_code:'',//邀请码
    shenfen_reg: '普通用户', //身份
    idcard: '',//身份证
    shenfen: ['普通用户', '业主', '中介机构'],
    yezhu:false,
    xiangmu:'',//项目
    building:'',//楼号
    unit: '',//单元
    room: '',//房号
    bank_card:'',//银行卡号
    bank_name:'',//开户行
    idcard:'',//身份证号
    resendTime: 60,//验证码重新发送时间 要与verificationTime保持一致
    verification: '', //验证码
    verificationText: '发送',
    verificationTime: 60,
    sending: false,
    latitude: '',//当前位置纬度
    longitude: '',//当前位置经度
    district: '',//当前位置是否是龙山县
  },
  // 获取验证码
  getVerification() {
    let _this = this;
    if (_this.data.sending) {
      console.log('正在获取中');
      return false;
    }
    if (this.data.tel && (/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.data.tel))) {
      let time = _this.data.verificationTime;
      let data = {
        pid: _this.data.pid,
        mobile: _this.data.tel,
        type: 'agent'
      }
      globalData.sendPost('captcha/send', data).then(res => {
        if (res.status == 1) {
          globalData.showHint(res.message);
        } else {
          globalData.showHint(res.message);
        }
      })
      let timer = setInterval(function () {
        time--;
        if (time == 0) {
          clearInterval(timer);
          _this.setData({
            verificationText: '发送',
            verificationTime: _this.data.resendTime,
            sending: false
          })
        } else {
          _this.setData({
            verificationText: time + 's',
            verificationTime: time,
            sending: true
          })
        }
      }, 1000)
    } else {
      wx.showToast({
        title: '请填写正确电话',
        icon: 'none'
      })
    }
  },
  // input输入事件
  inputChange(event) {
    let key = event.currentTarget.dataset.key;
    let value = event.detail.value;
    this.setData({
      [key]: value
    })
  },
  //input失去焦点事件
  bindblur(event){
    var _this = this;
    let key = event.currentTarget.dataset.key;
    let value = event.detail.value;
    _this.setData({
      [key]: value
    });
    if (!/^\d{16,19}$/g.test(value)) {
      getApp().globalData.showHint('银行卡号错误');
      return false;
    }else{
      wx.request({
        url: 'https://ccdcapi.alipay.com/validateAndCacheCardInfo.json', //仅为示例，并非真实的接口地址
        data: {
          cardNo:value,
          cardBinCheck: 'true'
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          console.log(res)
          console.log(res.data.bank)
          _this.setData({
            bank_name: banklist.dataList[res.data.bank]
          })
        }
      })
    }
  },
  //身份改变
  changeShenfen(e){
    this.setData({
      index: e.detail.value,
      shenfen_reg: this.data.shenfen[e.detail.value]
    })
    
    var shenfen_num = this.data.index;
    if (shenfen_num==1){
      this.setData({
        yezhu:true
      })
    }else{
      this.setData({
        yezhu: false
      })
    }
    console.log(this.data.shenfen_reg)
  },
  //确认提交
  tuijianReg() {
    if(this.data.index == 1){
      if (!this.data.building) {
        getApp().globalData.showHint('请填写楼栋号');
        return false;
      }
      if (!this.data.unit) {
        getApp().globalData.showHint('请填写单元号');
        return false;
      }
      if (!this.data.room) {
        getApp().globalData.showHint('请填写房间号');
        return false;
      }
    }
    if (!this.data.name) {
      getApp().globalData.showHint('请输入姓名');
      return false;
    }
    if (!this.data.tel || (!/^1[3|5|6|7|8|9]\d{9}$/.test(this.data.tel))) {
      getApp().globalData.showHint('电话错误');
      return false;
    }
    if (!this.data.verification) {
      getApp().globalData.showHint('验证码不能为空');
      return false;
    }
    if (!this.data.shenfen_reg) {
      getApp().globalData.showHint('请选择您的身份');
      return false;
    }
    // if (!this.data.bank_card) {
    //   getApp().globalData.showHint('银行卡号错误');
    //   return false;
    // }
    if (!this.data.idcard || !util.checkIdCard(this.data.idcard)) {
      getApp().globalData.showHint('身份证号错误');
      return false;
    }
    var idcard = this.data.idcard;
    var idcard_6 = idcard.substring(0, 6);
    if (idcard_6!=433130){
      getApp().globalData.showHint('仅限户籍为龙山县人注册');
      return false;
    }
    // if (this.data.district != "龙山县") {
    //   getApp().globalData.showHint('很抱歉！仅限龙山县用户注册');
    //   return false;
    // }
    let data = {
      pid: this.data.pid,
      openid: globalData.openid,
      name: this.data.name,
      mobile: this.data.tel,
      invite_code: this.data.share_code,
      captcha: this.data.verification,
      identity: this.data.shenfen_reg,
      bank_card: this.data.bank_card,
      bank_name: this.data.bank_name,
      idcard:this.data.idcard
    }
    if (this.data.index == 1){
      data.project = this.data.xiangmu,
      data.building = this.data.building,
      data.unit = this.data.unit,
      data.room = this.data.room
    }
    globalData.sendPost('custom/agent-reg', data).then(res => {
      console.log(res)
      if (res.status == 1) {
        var user_id = res.data.user_id;
        var identity = res.data.identity;
        var invite_code = res.data.invite_code;
        var invite_qrcode = res.data.invite_qrcode;
        wx.reLaunch({
          url: '../tuijian/index?user_id=' + user_id + '&identity=' + identity + '&invite_code=' + invite_code + '&invite_qrcode=' + invite_qrcode,
        })
      } else {
        globalData.showHint(res.msg);
        return false;
      }
    })
    return true;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.code){
      // console.log("has code");
      var code = decodeURIComponent(options.code);
      console.log(code);
      this.setData({
        share_code: code
      })
      if (app.globalData.employId && app.globalData.employId != '') {
        this.setData({
          showModal:app.globalData.login,
        });
        this.getLogin();
      } else {
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        app.employIdCallback = employId => {
          if (employId != '') {
            this.setData({
              showModal: app.globalData.login,
            });
            this.getLogin();
          }
        }
      }
      if (app.globalData.userInfo) {
        this.setData({
          userInfo: app.globalData.userInfo,
          hasUserInfo: true
        })
      } else if (this.data.canIUse) {
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        app.userInfoReadyCallback = res => {
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      } else {
        // 在没有 open-type=getUserInfo 版本的兼容处理
        wx.getUserInfo({
          success: res => {
            app.globalData.userInfo = res.userInfo
            this.setData({
              userInfo: res.userInfo,
              hasUserInfo: true
            })
          }
        })
      }
    }
    else {
      // console.log("no code");
    }
    this.getAddress();
    this.setData({
      xiangmu: options.project_name,
      pid: options.pid ? options.pid:globalData.pid,
    })
    
  },
  getUserInfo: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  //获取当前地址（是否在龙山县）
  getAddress() {
    var _this = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        _this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        // getApp().globalData.showHint("当前位置纬度"+_this.data.latitude+"当前位置经度"+_this.data.longitude);
        let key;
        if (globalData.pid == 35) {
          key = "ANXBZ-RPG34-YQ2U7-DY3IM-RVXVK-D3FUN"
        } else if (globalData.pid == 34) {
          key = "SZBBZ-Z7N3K-JI3J3-ANUJT-N7JIO-7TBOS"
        }
        console.log(key);
        let data = {
          location: _this.data.latitude + "," + _this.data.longitude,
            key
        }
        globalData.sendPost('https://apis.map.qq.com/ws/geocoder/v1', data).then(res => {
          // console.log(res)
          if (res.status == 0) {
            _this.setData({
              district: res.result.address_component.district
            })
            // getApp().globalData.showHint(_this.data.district);
          } else {
            globalData.showHint(res.msg);
            return false;
          }
        })
      }
    })
  },
  //获取是否登录
  getLogin(){
      let data = {
        openid: globalData.openid
      }
      console.log(data);
      globalData.sendPost('custom/check-login', data).then(res => {
        console.log(res)
        if (res.status == 1) {
          var user_id = res.data.user_id;
          var invite_code = res.data.invite_code;
          var invite_qrcode = res.data.invite_qrcode;
          var identity = res.data.identity;
          wx.reLaunch({
            url: '../tuijian/index?user_id=' + user_id + '&invite_code=' + invite_code + '&invite_qrcode=' + invite_qrcode + '&identity=' + identity,
          })
        }
      })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})